<?php

namespace app\store\controller\neworder;

use app\store\model\Invoice as InvoiceModel;
use think\Request;
use app\store\controller\Controller;
use think\Db;
class Invoice extends Controller
{
    /**
     * 开票申请列表
     */
    public function index(Request $request)
    {
        $keyword    = trim($request->get('keyword', ''));
        $start_time = trim($request->get('start_time', ''));
        $end_time   = trim($request->get('end_time', ''));
        $status     = input('get.status', '', 'trim'); // 0/1/2/3 或 空
    // 状态筛选
        
        // 基础查询：发票表 i
        $query = Db::name('invoice')->alias('i')
            // 关联就诊人（拿姓名/电话）
            ->join('user_jiuzhen uj', 'uj.user_id = i.user_id', 'LEFT')
            // 关联订单（拿订单号）
            ->join('order o', 'o.order_id = i.order_id', 'LEFT')
            ->field([
                'i.*',
                'uj.name'    => 'patient_name',
                'uj.phone'   => 'patient_phone',
                'o.order_no' => 'order_no',
            ])
            ->group('i.invoice_id');

        // 关键词：订单ID、订单号、姓名、手机号、邮箱、税号、抬头、备注
        if ($keyword !== '') {
            $query->where(function($q) use ($keyword) {
                $like = "%{$keyword}%";
                $q->where('i.order_id', 'like', $like)
                ->whereOr('o.order_no', 'like', $like)
                ->whereOr('uj.name', 'like', $like)
                ->whereOr('uj.phone', 'like', $like)
                ->whereOr('i.email', 'like', $like)
                ->whereOr('i.tax_number', 'like', $like)
                ->whereOr('i.invoice_title', 'like', $like)
                ->whereOr('i.remark', 'like', $like);
            });
        }

        // 时间区间（create_time 为字符串，直接 between）
        if ($start_time !== '' && $end_time !== '') {
            $query->where('i.create_time', 'between', [
                $start_time . ' 00:00:00',
                $end_time   . ' 23:59:59'
            ]);
        }
        if ($status !== '' && in_array($status, ['0','1','2','3'], true)) {
            $query->where('i.status', (int)$status);
        }
        // 排序 + 分页（保留查询参数，分页链接正确）
        $list = $query->order('i.create_time desc')
            ->paginate(15, false, [
                'query' => request()->request()
            ]);

        // 枚举映射（给前端更易读）
        $list->each(function($row){
        // 发票方式
        $row['invoice_type_text'] = $row['invoice_type'] == '1' ? '邮寄' : '邮箱';
        // 抬头类型
        $row['title_type_text']   = $row['title_type'] == '1' ? '个人' : '单位';
        // 状态
        $statusMap = [
            0 => '待处理',
            1 => '已开票',
            2 => '已邮寄/已发送',
            3 => '驳回',
        ];
        $row['status_text'] = $statusMap[(int)$row['status']] ?? ('状态'.$row['status']);

        // ===== 关键：把 null 和 "null" 都清理成空字符串 =====
        $fieldsToClean = [
            'consignee_name',
            'consignee_mobile',
            'consignee_address',
            'invoice_content',
            'tax_number',
            'email',
            'invoice_title',
            'remark'
        ];
        foreach ($fieldsToClean as $field) {
            if (!isset($row[$field]) || $row[$field] === null || trim($row[$field]) === 'null') {
                $row[$field] = '';
            }
        }

        return $row;
        });
        return $this->fetch('index', compact('list', 'keyword', 'start_time', 'end_time'));
    }


    /**
     * 查看详情
     */
    public function detail($invoice_id)
    {
        $model = InvoiceModel::detail($invoice_id);
        return $this->fetch('detail', compact('model'));
    }

    /**
     * 处理开票
     */
    public function handle($invoice_id)
    {
        $model = InvoiceModel::detail($invoice_id);
        if (request()->isPost()) {
            $status = input('post.status');
            $remark = input('post.remark', '');
            if ($model->save([
                'status' => $status,
                'remark' => $remark,
                'update_time' => time()
            ])) {
                return $this->renderSuccess('处理成功');
            }
            return $this->renderError('处理失败');
        }
        return $this->fetch('handle', compact('model'));
    }
    public function setStatus()
    {
        $invoiceId = (int)input('post.invoice_id');
        $status    = (int)input('post.status');
        $remark    = trim(input('post.remark', ''));

        if (!$invoiceId) {
            return $this->renderError('缺少参数 invoice_id');
        }
        if (!in_array($status, [0,1,2,3], true)) {
            return $this->renderError('状态不合法');
        }

        /** @var InvoiceModel $model */
        $model = InvoiceModel::get($invoiceId);
        if (!$model) {
            return $this->renderError('记录不存在');
        }

        // 你的表 create_time/update_time 是字符串，手动写入
        $save = [
            'status'      => $status,
            'remark'      => $remark,
            'update_time' => date('Y-m-d H:i:s'),
        ];

        // 如需联动更多字段（比如已邮寄时写入快递单号），可以继续扩展

        if (false === $model->save($save)) {
            return $this->renderError('保存失败');
        }
        return $this->renderSuccess('更新成功');
    }
    /**
     * 导出当前筛选（CSV）
     */
    public function export()
    {
        $keyword    = input('get.keyword', '', 'trim');
        $start_time = input('get.start_time', '', 'trim');
        $end_time   = input('get.end_time', '', 'trim');
        $status     = input('get.status', '', 'trim');

        $query = Db::name('invoice')
            ->alias('i')
            ->join('order o', 'o.order_id = i.order_id', 'LEFT')
            ->join('user_jiuzhen uj', 'uj.user_id = i.user_id', 'LEFT')
            ->field('i.*, o.order_no, uj.name as patient_name, uj.phone as patient_phone');

        if ($keyword !== '') {
            $query->where(function($q) use ($keyword) {
                $q->where('i.order_id', 'like', "%{$keyword}%")
                  ->whereOr('o.order_no', 'like', "%{$keyword}%")
                  ->whereOr('uj.name', 'like', "%{$keyword}%")
                  ->whereOr('uj.phone', 'like', "%{$keyword}%")
                  ->whereOr('i.email', 'like', "%{$keyword}%")
                  ->whereOr('i.tax_number', 'like', "%{$keyword}%")
                  ->whereOr('i.invoice_title', 'like', "%{$keyword}%")
                  ->whereOr('i.remark', 'like', "%{$keyword}%");
            });
        }
        if ($status !== '' && in_array($status, ['0','1','2','3'], true)) {
            $query->where('i.status', (int)$status);
        }
        if ($start_time !== '' && $end_time !== '') {
            $query->whereBetween('i.create_time', [
                $start_time . ' 00:00:00',
                $end_time   . ' 23:59:59'
            ]);
        }

        $rows = $query->order('i.create_time desc')->select();

        // 组装 CSV
        $header = [
            '开票ID','用户姓名','电话','订单ID','订单号','抬头类型','发票抬头',
            '税号','开票内容','金额','方式','收件人/邮箱','备注','状态','创建时间'
        ];

        $filename = 'invoice_' . date('Ymd_His') . '.csv';
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment;filename=' . $filename);
        // BOM 解决中文乱码
        echo "\xEF\xBB\xBF";

        $fp = fopen('php://output', 'w');

        fputcsv($fp, $header);

        foreach ($rows as $r) {
            $titleType  = ($r['title_type'] == '2') ? '单位' : '个人';
            $typeText   = ($r['invoice_type'] == '2') ? '邮箱' : '邮寄';
            $statusText = ['待处理','已开票','已邮寄/已发送','驳回'][(int)$r['status']] ?? '—';

            if ($r['invoice_type'] == '1') {
                // 邮寄
                $recv = trim(($r['consignee_name'] ?: '—') . ' ' . ($r['consignee_mobile'] ?: '—') . ' ' . ($r['consignee_address'] ?: '—'));
            } else {
                // 邮箱
                $recv = $r['email'] ?: '—';
            }

            fputcsv($fp, [
                $r['invoice_id'],
                $r['patient_name'] ?: '—',
                $r['patient_phone'] ?: '—',
                $r['order_id'] ?: '—',
                $r['order_no'] ?: '—',
                $titleType,
                $r['invoice_title'],
                $r['tax_number'],
                $r['invoice_content'],
                $r['amount'],
                $typeText,
                $recv,
                $r['remark'],
                $statusText,
                $r['create_time'],
            ]);
        }

        fclose($fp);
        exit;
    }
}